package org.harsh.common.net;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuhaibo on 2024/7/17.
 */
@Slf4j
public class PingUtil {

    public enum Backend {
        UNIX {
            @Override
            public PingResult getResult(List<String> output) {
                return new UnixPingResult(output);
            }

        },

        WINDOWS_zhCN {
            @Override
            public PingResult getResult(List<String> output) {
                return new WinPingResult(output);
            }

        };

        public abstract PingResult getResult(List<String> output);
    }

    public static PingResult ping(PingArguments ping, Backend backend) {

        try {

            Process p;

            String command = ping.getCommand(backend);
            p = Runtime.getRuntime().exec(command);
            p.waitFor();

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"));

            String s;

            List<String> lines = new ArrayList<String>();
            while ((s = stdInput.readLine()) != null) {
                lines.add(s);
            }

            p.destroy();

            return backend.getResult(lines);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("【节点连通性检查】节点不可达");
        }
        return null;

    }
}
